package com.chiwen.common.utils.ip;

import com.chiwen.common.exception.ServiceException;
import com.chiwen.common.utils.StringUtils;
import com.chiwen.common.utils.spring.SpringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;

/**
 * 获取IP方法
 * 
 * @author Dipper
 */
public class VbUtils
{
    /**
     * 获取客户端IP
     * 
     * @param request 请求对象
     * @return IP地址
     */

    public static String validationSign(HttpServletRequest request){


        //依次检查各变量是否存在？
        String privateKey = request.getHeader("privateKey");
        if (StringUtils.isBlank(privateKey)) {
//            throw new ServiceException("请传入正确 私钥数据");
            throw new ServiceException("无效请求heard");
        }
        String timestampStr = request.getHeader("timestamp");
        if (StringUtils.isBlank(timestampStr)) {
//            throw new ServiceException("请传入正确 时间戳数据");
            throw new ServiceException("无效请求heard");
        }
        String sign = request.getHeader("sign");
        if (StringUtils.isBlank(sign)) {
//            throw new ServiceException("请传入正确 签名数据");
            throw new ServiceException("无效请求heard");
        }


        long timestamp = 0;
        try {
            timestamp = Long.parseLong(timestampStr);
        } catch (Exception e) {
            throw new ServiceException("时间参数不正确");
        }
        //前端的时间戳与服务器当前时间戳相差如果大于180，判定当前请求的timestamp无效 时间戳与当前时间差距过3分钟
        if (Math.abs(timestamp - System.currentTimeMillis() / 1000) > 180) {
//            throw new ServiceException("请传入正确 时间戳数据");
        }
        final String bytes = Md5Info("privateKey=" + privateKey + "&timestamp=" + timestamp);
        // 比对上了
        if(bytes.equals(sign)){
//            SpringUtils.getBean(ISysUserService.class)
            return privateKey;
        }else{
            throw new ServiceException("加密方式错误");
        }

    }


    public static String Md5Info(String str){
        //结果字符串
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString().toUpperCase();
            System.out.println("MD5(" + str + ",32大写) = " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}